package cn.uniquesoft.controller;

import java.io.File;
import java.util.Date;

import cn.uniquesoft.util.ContextUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.uniquesoft.controller.base.BaseController;
import cn.uniquesoft.service.IAdvertiseService;
import cn.uniquesoft.util.DateUtil;
import cn.uniquesoft.util.FileUpUtil;
import cn.uniquesoft.vo.AdvertiseVO;
import cn.uniquesoft.vo.AnswerVO;
import cn.uniquesoft.vo.base.BaseVO;
@Controller
@RequestMapping(value = "/advertise")
@SuppressWarnings("unused")
public class AdvertiseController extends BaseController<AdvertiseVO> {
	
	private IAdvertiseService advertiseService;
	public AdvertiseController(IAdvertiseService advertiseService) {
		super();
		this.advertiseService = advertiseService;
		this.baseService = advertiseService;
		this.indexName = "advertise/index";
	}
	
	
	@Override
	@RequestMapping(value = "/save")
	@ResponseBody
	public AnswerVO save(AdvertiseVO item) {
		AnswerVO answerVO = new AnswerVO();
		try {
			MultipartFile file = item.getUpfile();
			if(file.getSize()>0){

//				File path = new File(ResourceUtils.getURL("classpath:").getPath());
//				if(!path.exists()) path = new File("");
				// 获得上传文件原始名
				String oldname = file.getOriginalFilename();
				// 算出后缀名
				String ext = oldname.substring(oldname.lastIndexOf("."));
				// 文件名为：问题名称 + image + UUID + 后缀
				String fileName = "advertise" + DateUtil.date2timestamp(new Date(), DateUtil.FORMAT_DATETIME) + ext;
				String tomurl = ContextUtil.getRequest().getSession().getServletContext().getRealPath("/");
				String filepath = "files"+ File.separator + "advertise" + File.separator;
				String fileFolder = tomurl+filepath;
				File upload = new File(fileFolder);
				if(!upload.exists()) upload.mkdirs();
				File localFile = new File(fileFolder, fileName);
				
				// 直接写入到后台服务器，简单且快
				file.transferTo(localFile);
				item.setCpicname(oldname);
				item.setCpicpath(filepath+fileName);
				item.setCpicsize(FileUpUtil.convertFileSize(file.getSize()));
			}
			this.advertiseService.save(item);
			int itemId = ((BaseVO) item).getIid();
			if (itemId > 0) {
				answerVO.setSuccess(true);
				answerVO.setMsg("新增成功!");
			} else {
				answerVO.setSuccess(false);
				answerVO.setMsg("新增失败!");
			}
			answerVO.setData(itemId);
		} catch (Exception e) {
			e.printStackTrace();
			answerVO.setSuccess(false);
			answerVO.setMsg("新增失败," + e.getMessage());
		}
		return answerVO;
	}
		@Override
		@RequestMapping(value = "/edit")
		@ResponseBody
		public AnswerVO edit(AdvertiseVO item) {
			AnswerVO answerVO = new AnswerVO();
			try {
				MultipartFile file = item.getUpfile();
				if(file.getSize()>0){

//					File path = new File(ResourceUtils.getURL("classpath:").getPath());
					// 获得上传文件原始名
					String oldname = file.getOriginalFilename();
					// 算出后缀名
					String ext = oldname.substring(oldname.lastIndexOf("."));
					// 文件名为：问题名称 + image + UUID + 后缀
					String fileName = "advertise" + DateUtil.date2timestamp(new Date(), DateUtil.FORMAT_DATETIME) + ext;
					String tomurl = ContextUtil.getRequest().getSession().getServletContext().getRealPath("/");
					String filepath = "files"+ File.separator + "advertise" + File.separator;
					String fileFolder = tomurl+filepath;
					File upload = new File(fileFolder);
					if(!upload.exists()) upload.mkdirs();
					File localFile = new File(fileFolder, fileName);
					
					// 直接写入到后台服务器，简单且快
					file.transferTo(localFile);
					item.setCpicname(oldname);
					item.setCpicpath(filepath+fileName);
					item.setCpicsize(FileUpUtil.convertFileSize(file.getSize()));
				}
				int result = this.baseService.edit(item);
				if (result > 0) {
					answerVO.setSuccess(true);
					answerVO.setMsg("修改成功!");
				} else {
					answerVO.setSuccess(false);
					answerVO.setMsg("修改失败!");
				}
				answerVO.setData(result);
			} catch (Exception e) {
				answerVO.setSuccess(false);
				answerVO.setMsg("修改失败," + e.getMessage());
			}

			return answerVO;
		}
		public static String convertFileSize(long size) {
	        long kb = 1024;
	        long mb = kb * 1024;
	        long gb = mb * 1024;
	 
	        if (size >= gb) {
	            return String.format("%.1f GB", (float) size / gb);
	        } else if (size >= mb) {
	            float f = (float) size / mb;
	            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
	        } else if (size >= kb) {
	            float f = (float) size / kb;
	            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
	        } else
	            return String.format("%d B", size);
	    }
}
